<template>
    <el-main>
        <el-form>
            <el-form-item>
                <el-button type="success" :icon="Plus" @click="addDeptBtn" v-permission="5">新增</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="tableDate.deptList" style="width: 100%" max-height="600px" row-key="id" border
            :tree-props="{ children: 'children' }" default-expand-all>
            <el-table-column prop="name" label="部门名称" width="220" />
            <el-table-column prop="director" label="负责人" />
            <el-table-column prop="director_tel" label="联系方式" />
            <el-table-column prop="ord" label="排序" />
            <el-table-column prop="remarks" label="注释" />
            <el-table-column width="200" align="center" label="操作" fixed="right">
                <template #default="scope">
                    <el-button size="small" type="primary" :icon="Edit" @click="editDeptBtn(scope.row)"
                        v-permission="6">编辑</el-button>
                    <DelBtn @delBtn="delDeptBtn(scope.row)" :permission="7"></DelBtn>
                </template>
            </el-table-column>
        </el-table>
    </el-main>
    <!-- 新增或编辑弹窗 -->
    <DeptAddAndEdit ref="deptRef" :deptParentList="tableDate.deptParentList" @newGetDeptList="getDeptList">
    </DeptAddAndEdit>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue'

import { Plus, Edit } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus"

import DeptAddAndEdit from './DeptAddAndEdit.vue'
import DelBtn from '@/components/DelBtn.vue'
import { DialogType } from '@/hooks/useDialog'
import { getDeptApi, delDeptApi } from '@/http/api/department'


// 定义表格数据
const tableDate = reactive({
    deptList: [],
    deptParentList: [{ value: 0, label: '顶级部门', children: [] },]
})
//获取数据赋值给列表
const getDeptList = async () => {
    await getDeptApi().then((res) => {
        if (res && res.code == 200) {
            tableDate.deptList = res.data
            tableDate.deptParentList[0].children = res.data
        }
    })
}
// 子组件DeptAddAndEdit的ref属性
const deptRef = ref<InstanceType<typeof DeptAddAndEdit>>()
// 添加部门
const addDeptBtn = () => {
    deptRef.value?.onShow(DialogType.ADD, '添加部门')
}
// 修改部门
const editDeptBtn = (editData: any) => {
    deptRef.value?.onShow(DialogType.EDIT, '修改部门', editData)
}
// 删除部门
const delDeptBtn = async (delData: any) => {
    if (delData.children && delData.children.length > 0) {
        ElMessage.warning('该部门下面还有子部门，不能删除！')
    } else {
        await delDeptApi(delData.id).then(res => {
            if (res && res.code == 204) {
                ElMessage.success('删除成功！')
                getDeptList()
            } else {
                ElMessage.error(res.msg)
            }
        })
    }

}

onMounted(() => {
    getDeptList()
})

</script>

<style scoped lang='scss'>
</style>